package com.xiaoyu.cloud.handler;


import com.xiaoyu.common.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @author zgb
 * @desc ...
 * @date 2022-06-21 12:03:54
 */

@Slf4j
public class HttpClientResponseHandler implements ResponseHandler {

    @Override
    public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        R r = new R();
        r.setSuccess(false);
        r.setCode("400");
        r.setData(null);
        if (response == null) {
            r.setMsg("httpResponse == null");
            return r;
        }
        log.debug("httpResponse：" + response);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine == null) {
            r.setMsg("statusLine == null");
            return r;
        }
        log.debug("statusLine：" + statusLine);
        int statusCode = statusLine.getStatusCode();

        if (statusCode < 200 && statusCode >= 300) {
            throw new ClientProtocolException("Unexpected response statusCode: " + statusCode);
        }


        log.debug("statusCode：" + statusCode);
        String reasonPhrase = statusLine.getReasonPhrase();
        log.debug("reasonPhrase：" + reasonPhrase);


        Header[] allHeaders = response.getAllHeaders();
        log.debug("allHeaders：" + allHeaders);

        HttpEntity entity = response.getEntity();
        log.debug("entity：" + entity);
        String responseJson = entity != null ? EntityUtils.toString(entity, "UTF-8") : null;

        r.setData(responseJson);
        r.setMsg(reasonPhrase);
        r.setCode(Integer.toString(statusCode));
        if (Objects.equals(statusCode, 200)) {
            r.setSuccess(true);
        } else {
            r.setSuccess(false);
        }

        return r;


    }
}
